package cn.bearspark.common.parse.html;

import cn.bearspark.common.parse.Parser;

/**
 * div 标签的解析器
 *
 * @author f
 */
public class TagDivParser extends Parser<HtmlTextParseContext> {
    @Override
    public void parse() {
        HtmlTextParseContext context = pipeline().getContext();
        String src = context.getBody();
        int index = 0;
        while (true) {
            int openIndex = src.indexOf("<div>", index);
            if (openIndex == -1) {
                context.setBody(src);
                return;
            }
            int closeIndex = src.indexOf("</div>", openIndex);
            src = src.substring(0, openIndex) +
                  "<d" +
                  src.substring(openIndex + "<div>".length(), closeIndex) +
                  ">" +
                  src.substring(closeIndex + "</div>".length());
            index = closeIndex + "</div>".length();
        }
    }

    @Override
    public void unparse() {
        HtmlTextParseContext context = pipeline().getContext();
        String tar = context.getBody();
        int index = 0;
        while (true) {
            int openIndex = tar.indexOf("<d", index);
            if (openIndex == -1) {
                context.setBody(tar);
                return;
            }
            int closeIndex = tar.indexOf(">", openIndex);
            tar = tar.substring(0, openIndex) +
                  "<div>" +
                  tar.substring(openIndex + "<d".length(), closeIndex) +
                  "</div>" +
                  tar.substring(closeIndex + ">".length());
            index = tar.indexOf("</div>", openIndex) + "</div>".length();
        }
    }
}
